import { createSlice } from '@reduxjs/toolkit';
import { addElementToArray } from '@/utils/array';
import { HomeMenuState, TreeNode } from '@/domain/tree';

const initialState: HomeMenuState = { menus: [], activeKey: 'develop-1-1' };

const homeMenuSlice = createSlice({
    name: 'homeMenus',
    initialState,
    reducers: {
        addMenu: (state, actions) => {
            if (!actions.payload) {
                console.error("要添加的菜单为undefined！！");
                return;
            }
            state.menus = addElementToArray(state.menus, actions.payload, (arr: TreeNode[], newE: TreeNode) => {
                return arr.some(e => e.key === newE.key);
            })
        },
        deleteMenu: (state, actions) => {
            if (!actions.payload) {
                console.error("要删除的菜单为undefined！！");
                return;
            }
            state.menus.some((item, idx) => {
                if (item.key === actions.payload.key) {
                    state.menus.splice(idx, 1);
                    return true;
                }
            })
        },
        setActiveKey: (state, actions) => {
            state.activeKey = actions.payload;
        },
    },
});

export const { addMenu, deleteMenu, setActiveKey } = homeMenuSlice.actions;

export default homeMenuSlice.reducer;

export type HomeMenuRootState = { homeMenus: HomeMenuState };